package com.internship.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;









import com.internship.model.Admin;
import com.internship.model.DepartmentInfo;
import com.internship.model.School;
import com.internship.model.StudentInfo;
import com.internship.model.TeacherInfo;
import com.internship.page.Page;
import com.internship.service.AdminService;
import com.internship.service.DepartmentInfoService;
import com.internship.service.NotifyService;
import com.internship.service.PracticeChangeService;
import com.internship.service.QuestionService;
import com.internship.service.SchoolService;
import com.internship.service.StudentInfoService;
import com.internship.service.TeacherInfoService;
import com.internship.service.Const;
import com.internship.util.DesTool;

@Controller
@RequestMapping("admin")
public class AdminController {
	private final Logger logger = Logger.getLogger(AdminController.class);
	
	@Autowired
	private AdminService adminService;

	@Autowired
	private TeacherInfoService teacherInfoService;
	@Autowired
	private StudentInfoService studentInfoService;
	@Autowired
	private DepartmentInfoService 	departmentInfoService;
	@Autowired
	private QuestionService 	questionService;
	@Autowired
	private SchoolService 	schoolService;
	@Autowired
	private PracticeChangeService 	practiceChangeService;
	@Autowired
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}
	@Autowired
	private NotifyService notifyService;
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	
	public String getUserRoleStr(int role) {
		switch (role) {
		case 1:
			return "系统管理员";
		case 2:
			return "学校管理员";
		case 3:
			return "院系管理员";
		}
		return "";
	}
	private void saveSessionAdmin(Admin admin) {
		HttpSession session = getSession();
		session.setAttribute(Const.SESSION_ACCOUNT, admin.getTeacherNumber());
		session.setAttribute(Const.USER_NAME, admin.getTeacherName());
		session.setAttribute(Const.USER_DEPARTMENT_CODE, admin.getDeptNumber());
		session.setAttribute(Const.USER_DEPARTMENT_NAME, admin.getDeptName());
		session.setAttribute(Const.USER_ROLE, admin.getUserRole());
		session.setAttribute(Const.USER_ROLE_NAME, getUserRoleStr(admin.getUserRole()));
	}
	private void saveSessionTeacher(TeacherInfo teacherInfo) {
		HttpSession session = getSession();
		session.setAttribute(Const.SESSION_ACCOUNT, teacherInfo.getZGH());
		session.setAttribute(Const.USER_NAME, teacherInfo.getXM());
		/*session.setAttribute(Const.USER_DEPARTMENT_CODE, teacherInfo.getDeptNumber());*/
		session.setAttribute(Const.USER_DEPARTMENT_NAME, teacherInfo.getBM());
		session.setAttribute(Const.USER_PHONE, teacherInfo.getLXDH());
		session.setAttribute(Const.USER_SEX, teacherInfo.getXB());
		session.setAttribute(Const.USER_ROLE, Const.ROLE_TEACHER);
		session.setAttribute(Const.USER_ROLE_NAME, Const.ROLE_TEACHER_NAME);
	}
	private void saveSessionStu(StudentInfo studentInfo) {
		HttpSession session = getSession();
		session.setAttribute(Const.SESSION_ACCOUNT, studentInfo.getXH());
		session.setAttribute(Const.USER_NAME, studentInfo.getXM());
		session.setAttribute(Const.GRADE, studentInfo.getDQSZJ());
		session.setAttribute(Const.USER_PHONE, studentInfo.getLXDH());
		session.setAttribute(Const.USER_SEX, studentInfo.getXB());
		session.setAttribute(Const.USER_DEPARTMENT_NAME, studentInfo.getXY());
		session.setAttribute(Const.USER_CLASSINFO, studentInfo.getXZB());
		session.setAttribute(Const.USER_ROLE, Const.ROLE_STUDENT);
		session.setAttribute(Const.USER_ROLE_NAME, Const.ROLE_STUDENT_NAME);
	}
	private void clearSession() {
		getSession().invalidate();
	}
	/*@RequestMapping("/main.do")
    public ModelAndView mainPage() {  
		logger.info("执行mainPage方法");
		ModelAndView mv = new ModelAndView("main");
		return mv;
	}*/

	@RequestMapping("/logout.do")
	public String logout() {
		clearSession();
		return "login";
	}
	
	@RequestMapping("/login.do")
	@ResponseBody
    public Object userLogin(@RequestParam String KEYDATA) {
		logger.info("执行userLogin方法");
		HttpSession session = getSession();
		String errInfo = "";
		JSONObject json = new JSONObject();
		String KEY[] = KEYDATA.split(",zt,");
	
		String role = KEY[2];	
		if(null == role || "".equals(role)|| role.equals("undefined")){
			errInfo = "nullrole"; //角色为空
		}else{
						
			if (role.equals("1")) {
				
			Admin admin = adminService.getAdminByteacherNumber(KEY[0]);
					if(admin != null && DesTool.decode(admin.getPasswrod()).equals(KEY[1])) {
						saveSessionAdmin(admin);
						errInfo = "success";
						logger.info("------userLogin  userLogin = " + KEY[0]);
					}else {
						errInfo = "usererror";		
						}
				 }else if (role.equals("2")) {
					 TeacherInfo teacherInfo = teacherInfoService.geTeacherInfoByZGH(KEY[0]);
					 if(teacherInfo != null && DesTool.decode(teacherInfo.getPwd()).equals(KEY[1])) {
						 Admin user = adminService.getAdminByteacherNumber(teacherInfo.getZGH());
							if(user == null) {
								session.setAttribute(Const.USER_ROLE, Const.ROLE_TEACHER);
								DepartmentInfo departmentInfo=   departmentInfoService.getDepartmentInfo(teacherInfo.getBM());
								 session.setAttribute(Const.USER_DEPARTMENT_CODE, departmentInfo.getXYDM());
								session.setAttribute(Const.USER_ROLE_NAME, Const.ROLE_TEACHER_NAME);
							} else {
								session.setAttribute(Const.USER_ROLE, user.getUserRole());
								if(user.getUserRole()==1){
									session.setAttribute(Const.USER_ROLE_NAME,Const.ROLE_SCH_SITE_NAME);
								}
								if(user.getUserRole()==2){
									DepartmentInfo departmentInfo=   departmentInfoService.getDepartmentInfo(user.getDeptName());
									 session.setAttribute(Const.USER_DEPARTMENT_CODE, departmentInfo.getXYDM());
									session.setAttribute(Const.USER_ROLE_NAME,Const.ROLE_SCH_ADMIN_NAME);
								}
								if(user.getUserRole()==3){
									DepartmentInfo departmentInfo=   departmentInfoService.getDepartmentInfo(user.getDeptName());
									 session.setAttribute(Const.USER_DEPARTMENT_CODE, departmentInfo.getXYDM());
									session.setAttribute(Const.USER_ROLE_NAME,Const.ROLE_DEPT_ADMIN_NAME);
								}
							}
							saveSessionTeacher(teacherInfo);
							errInfo = "success";
							logger.info("------userLogin  userLogin = " + KEY[0]);
						}else {
							errInfo = "usererror";		
							}
					 }else if (role.equals("3")) {
						 StudentInfo studentInfo = studentInfoService.getStudentInfoByXH(KEY[0]);
						 if(studentInfo != null && DesTool.decode(studentInfo.getPwd()).equals(KEY[1])) {
							 DepartmentInfo departmentInfo=   departmentInfoService.getDepartmentInfo(studentInfo.getXY());
							 session.setAttribute(Const.USER_DEPARTMENT_CODE, departmentInfo.getXYDM());
							 saveSessionStu(studentInfo);
								errInfo = "success";
								logger.info("------userLogin  userLogin = " + KEY[0]);
							}else {
								errInfo = "usererror";		
								}
					}
			}
			
		json.put("result", errInfo);
		return json;
	}
	
	@RequestMapping("/index.do")
    public ModelAndView indexPage() {
		logger.info("执行indexPage方法");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("main");
		return mv;
	}
	@RequestMapping("/home.do")
    public ModelAndView home() {
		logger.info("执行home方法");
		ModelAndView mv = new ModelAndView();
		HttpSession session = getSession();
		if (String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("1")||String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("2")) {
		int QuestionCount = questionService.getHomeQuestionUnreadCount(null, null);
		int count = notifyService.getNotifyCount(0);
		int  PracticeChangeCount = practiceChangeService.getPracticeChangeCount(null, null);
		mv.addObject("QuestionCount", QuestionCount);
		mv.addObject("PracticeChangeCount", PracticeChangeCount);
		mv.addObject("count", count);
		}else if(String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("3")){
			int count = notifyService.getNotifyCount(Integer.parseInt(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT))));
			int QuestionCount = questionService.getHomeQuestionUnreadCount(String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_CODE)), null);
			int  PracticeChangeCount = practiceChangeService.getPracticeChangeCount(String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_CODE)), null);
			mv.addObject("QuestionCount", QuestionCount);
			mv.addObject("count", count);
			mv.addObject("PracticeChangeCount", PracticeChangeCount);
		}else if(String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("4")){
			int count = notifyService.getNotifyCount(Integer.parseInt(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT))));
			int QuestionCount = questionService.getHomeQuestionUnreadCount(null, String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			int  PracticeChangeCount = practiceChangeService.getPracticeChangeCount(null, String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			mv.addObject("QuestionCount", QuestionCount);
			mv.addObject("PracticeChangeCount", PracticeChangeCount);
			mv.addObject("count", count);
		}else {
			int count = notifyService.getNotifyCount(Integer.parseInt(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT))));
			mv.addObject("count", count);
		}
		mv.setViewName("home_page");
		return mv;
	}
	/**?
	 * 学校基本信息页面
	 * @return
	 */
	@RequestMapping("/school.do")
    public ModelAndView school() {
		logger.info("执行school方法");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("school_info");
		School  school =  schoolService.getSchool();
		mv.addObject("school", school);
		return mv;
	}
	
	/**?
	 * 修改学校信息
	 * @param id
	 * @param schoolName
	 * @param schoolAddress
	 * @param schoolPhone
	 * @param schoolWeb
	 * @param schoolIntroduzione
	 * @param schoolPerson
	 * @param schoolPersonPhone
	 * @param schoolPersonCharge
	 * @return
	 */
	@RequestMapping("/school_edit.do")
	@ResponseBody
	public JSONObject editSchool(@RequestParam("id")int  id,@RequestParam("schoolName") String schoolName,@RequestParam("schoolAddress") String schoolAddress ,@RequestParam("schoolPhone") String schoolPhone,@RequestParam("schoolWeb") String schoolWeb,@RequestParam("schoolIntroduzione") String schoolIntroduzione ,@RequestParam("schoolPerson") String schoolPerson,@RequestParam("schoolPersonPhone") String schoolPersonPhone,@RequestParam("schoolPersonCharge") String schoolPersonCharge) {
		JSONObject json = new JSONObject();
		School  school =  schoolService.getSchool();
		school.setSchoolName(schoolName);
		school.setSchoolIntroduzione(schoolIntroduzione);
		school.setSchoolPerson(schoolPerson);;
		school.setSchoolPersonCharge(schoolPersonCharge);
		school.setSchoolPersonPhone(schoolPersonPhone);
		school.setSchoolWeb(schoolWeb);
		school.setSchoolAddress(schoolAddress);
		school.setSchoolPhone(schoolPhone);
		int rel = schoolService.updateSchool(school);
		json.put("result", rel>0?"success":"error");
		return json;
	}
	/**？
	 * 角色信息页面
	 * @return
	 */
	@RequestMapping("/syetem.do")
    public ModelAndView Syetem() {
		logger.info("执行Syetem方法");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("syetem_role_list");
		return mv;
	}
	/**?
	 * 个人信息页面
	 * @return
	 */
	
	@RequestMapping("/selt.do")
    public ModelAndView selt() {
		logger.info("执行selt方法");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("self_info");
		return mv;
	}
	@RequestMapping("/user_edit.do")
	@ResponseBody
	public JSONObject editUser(@RequestParam("userPhone")String  userPhone) {
		JSONObject json = new JSONObject();
		try {
		HttpSession session = getSession();
		if (String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("2")||String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("3")||String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("4")) {
			TeacherInfo teacherInfo = teacherInfoService.geTeacherInfoByZGH(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			teacherInfo.setLXDH(userPhone);
			int rel = teacherInfoService.updatePhone(teacherInfo);
			json.put("result", rel>0?"success":"error");
			if (rel>0) {
				session.removeAttribute(Const.USER_PHONE);
				session.setAttribute(Const.USER_PHONE,
						userPhone);
			}
		}else if (String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("6")) {
			StudentInfo studentInfo = studentInfoService.getStudentInfoByXH(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
			studentInfo.setLXDH(userPhone);
			int rel = studentInfoService.updatePhone(studentInfo);
			json.put("result", rel>0?"success":"error");
			if (rel>0) {
				session.removeAttribute(Const.USER_PHONE);
				session.setAttribute(Const.USER_PHONE,
						userPhone);
			}
		}} catch (Exception ex) {
			ex.printStackTrace();
		}
		return json;
	}
	/**?
	 * 系统管理员
	 * @return
	 */
	@RequestMapping("/admin_list.do")
	public ModelAndView getAdminList() {
		return getAdminList(null,null,1);
	}
	private List<DepartmentInfo>  departmentInfoList = null;
	@RequestMapping("/admin_page_list.do")
	public ModelAndView getAdminList(@RequestParam("deptName") String deptName,@RequestParam("teacherName") String teacherName,@RequestParam int pageNumber) {
		Page<Admin> pageList = adminService.getAdminsList(deptName,teacherName, pageNumber);
		this.departmentInfoList = departmentInfoService.getDepartmentInfoList();
		ModelAndView mv = new ModelAndView("admin_info");
		mv.addObject("currentPage", pageNumber);
		mv.addObject("departmentInfoList", departmentInfoList);	
		mv.addObject("deptName", deptName);
		mv.addObject("teacherName", teacherName);
		mv.addObject("totalPage", pageList.getTotalPage());
		mv.addObject("totalCount", pageList.getTotalCount());
		mv.addObject("adminList", pageList.getResultList());
		return mv;
	}
	/**?
	 * 同步数据页面
	 * @return
	 */
	@RequestMapping("/synchronousData.do")
    public ModelAndView synchronousData() {
		logger.info("执行synchronousData方法");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("synchronous_data");
		return mv;
	}
	/**?
	 * 删除
	 * @param ZGH
	 * @return
	 */
		@RequestMapping("/delete.do")
		@ResponseBody
		public JSONObject delAdmin(@RequestParam String teacherNumber){
			JSONObject json = new JSONObject();
			int  rel= adminService.delAdmin(teacherNumber);
			json.put("result", rel > 0 ?"success":"error");
			 return json; 
		}
		/**?
		 * 指定为学校管理员
		 * @param teacherNumber
		 * @return
		 */
		@RequestMapping("/schoolAdministrators.do")
		@ResponseBody
		public JSONObject schoolAdministrators(@RequestParam String teacherNumber) {
			JSONObject json = new JSONObject();
			Admin admin = adminService.getAdminByteacherNumber(teacherNumber);
			admin.setUserRole(2);
			int rel = adminService.updateAdmin(admin);
			json.put("result", rel > 0 ?"success":"error");
			return json;
		}
}